<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class Address extends Model
{

    // 表名
    protected $name = 'kuyou_address';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取地址详情
     * @param int $id
     * @return array
     */
    public static function getArea($id){
        $area = (new Areas())->where(['id'=>$id])->find();
        if($area){
            return ['status'=>200,'msg'=>$area];
        }else{
            return ['status'=>500,'msg'=>'查询失败'];
        }
    }
    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->field("id,nickname,connect_name,connect_phone,connect_mobile,province,city,area,detail_address,post_code,is_default,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->field("id,nickname,connect_name,connect_phone,connect_mobile,province,city,area,detail_address,post_code,is_default,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->select())->toArray();
        }

        foreach ($list as $list_k=>$list_v){
            $area = self::getArea($list_v['province']);
            if($area['status']==200){
                $list[$list_k]['province_name'] = $area['msg']['name'];
            }

            $area = self::getArea($list_v['city']);
            if($area['status']==200){
                $list[$list_k]['city_name'] = $area['msg']['name'];
            }

            $area = self::getArea($list_v['area']);
            if($area['status']==200){
                $list[$list_k]['area_name'] = $area['msg']['name'];
            }
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->field("id,nickname,connect_name,connect_phone,connect_mobile,province,city,area,detail_address,post_code,is_default,FROM_UNIXTIME(createtime,'%Y-%m-%d %H:%i:%s') as createtime")->find();

        $area = self::getArea($detail['province']);
        if($area['status']==200){
            $detail['province_name'] = $area['msg']['name'];
        }

        $area = self::getArea($detail['city']);
        if($area['status']==200){
            $detail['city_name'] = $area['msg']['name'];
        }

        $area = self::getArea($detail['area']);
        if($area['status']==200){
            $detail['area_name'] = $area['msg']['name'];
        }

        return $detail;
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'nickname|简称'=>'require',
                'connect_name|联系人'=>'require',
                'connect_mobile|手机'=>'require|number',
                'province|省'=>'require|number',
                'city|市'=>'require|number',
                'detail_address|详细地址'=>'require',
                'post_code|邮编'=>'number',
                'is_default|是否默认'=>'require|in:0,1',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $area = new Areas();

                if($detail['province']>100000){
                    $province = $area->where(['adcode'=>$detail['province']])->value('id');
                }else{
                    $province = $area->where(['id'=>$detail['province']])->value('id');
                }
                if(empty($province)){
                    return ['status'=>500,'msg'=>'请选择省数据'];
                }
                $detail['province'] = $province;

                if($detail['city']>100000){
                    $city = $area->where(['adcode'=>$detail['city']])->value('id');
                }else{
                    $city = $area->where(['id'=>$detail['city']])->value('id');
                }
                if(empty($city)){
                    return ['status'=>500,'msg'=>'请选择市数据'];
                }
                $detail['city'] = $city;

                if(isset($detail['area']) && !empty($detail['area'])){
                    if($detail['area']>100000){
                        $area = $area->where(['adcode'=>$detail['area']])->value('id');
                    }else{
                        $area = $area->where(['id'=>$detail['area']])->value('id');
                    }
                    if(empty($area)){
                        return ['status'=>500,'msg'=>'区域数据错误'];
                    }
                    $detail['area'] = $area;
                }

                $model = new Address();
                $res = false;
                Db::startTrans();
                try {
                    if($detail['is_default']==1){
                        $model->where(['is_default'=>'1'])->update(['is_default'=>'0']);
                    }
                    $res = $model->allowField(true)->save($detail);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    return ['status'=>500,'msg'=>$e->getMessage()];
                }

                if($res){
                    return ['status'=>200,'msg'=>$model->id];
                }else{
                    return ['status'=>500,'msg'=>'添加失败'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|ID'=>'require|number',
                'nickname|简称'=>'require',
                'connect_name|联系人'=>'require',
                'connect_mobile|手机'=>'require|number',
                'province|省'=>'require|number',
                'city|市'=>'require|number',
                'detail_address|详细地址'=>'require',
                'post_code|邮编'=>'number',
                'is_default|是否默认'=>'require|in:0,1',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $model = new Address();
                $row = $model->where(['id'=>$detail['id']])->find();;
                if($row){

                    $area = new Areas();

                    if($detail['province']>100000){
                        $province = $area->where(['adcode'=>$detail['province']])->value('id');
                    }else{
                        $province = $area->where(['id'=>$detail['province']])->value('id');
                    }
                    if(empty($province)){
                        return ['status'=>500,'msg'=>'请选择省数据'];
                    }
                    $detail['province'] = $province;

                    if($detail['city']>100000){
                        $city = $area->where(['adcode'=>$detail['city']])->value('id');
                    }else{
                        $city = $area->where(['id'=>$detail['city']])->value('id');
                    }
                    if(empty($city)){
                        return ['status'=>500,'msg'=>'请选择市数据'];
                    }
                    $detail['city'] = $city;

                    if(isset($detail['area']) && !empty($detail['area'])){
                        if($detail['area']>100000){
                            $area = $area->where(['adcode'=>$detail['area']])->value('id');
                        }else{
                            $area = $area->where(['id'=>$detail['area']])->value('id');
                        }
                        if(empty($area)){
                            return ['status'=>500,'msg'=>'区域数据错误'];
                        }
                        $detail['area'] = $area;
                    }

                    $res = false;
                    Db::startTrans();
                    try {
                        if($detail['is_default']==1){
                            $model->where(['is_default'=>'1','id'=>['<>',$detail['id']]])->update(['is_default'=>'0']);
                        }
                        $res = $row->allowField(true)->save($detail);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                    }

                    if($res){
                        return ['status'=>200,'msg'=>'更新成功'];
                    }else{
                        return ['status'=>500,'msg'=>'更新失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'未查询到可更新数据'];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $res = (new Address())->where(['id'=>['in',$id]])->delete();
            if($res){
                return ['status'=>200,'msg'=>$res];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }
}
